package com.helloworld.chat.dao.impl;

import com.helloworld.chat.dao.FriendDao;
import com.helloworld.chat.entity.Friend;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by xdzy on 2017/6/29.
 */
@Repository
public class FriendDaoImpl implements FriendDao {
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void addFriend(Friend friend) {
        sessionFactory.getCurrentSession().save(friend);
    }

    @Override
    public Friend getFriend(int id) {
        return sessionFactory.getCurrentSession().get(Friend.class,id);
    }

    @Override
    public Friend getFriend(int uid, int fuid) {
        String hql="from Friend as f where f.uid=:uid and f.fu.id=:fuid";
        return sessionFactory.getCurrentSession().createQuery(hql,Friend.class)
                .setParameter("uid",uid).setParameter("fuid",fuid).uniqueResult();
    }

    @Override
    public List<Friend> getFriendsInGroup(int groupId) {
        String hql="from Friend as f where f.gid=:id";
        Query<Friend> query=sessionFactory.getCurrentSession().createQuery(hql,Friend.class);
        query.setParameter("id",groupId);
        return query.list();
    }

    @Override
    public void delete(Friend friend) {
        sessionFactory.getCurrentSession().delete(friend);
    }

    @Override
    public void update(Friend friend) {
        sessionFactory.getCurrentSession().update(friend);
    }
}
